<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 * Class	: M_s_users
 * 
 * Table	: s_users
 *  
 * @author Eko Junaidi Salam
 *
 */
class M_s_users extends CI_Model{

	function __construct(){
		parent::__construct();
	}
	
	/**
	 * Fungsi	: getAll
	 * 
	 * Untuk mengambil all-data
	 * 
	 * @param number $start
	 * @param number $page
	 * @param number $limit
	 * @return json
	 */
	function getAll($gid,$start, $page, $limit){
		$query = $this->db->query("SELECT USER_ID, USER_NAME, '[hidden]' AS USER_PASSWD FROM (vu_s_users) WHERE GROUP_ID = $gid")->result();
		$total  = $this->db->where('GROUP_ID', $gid)->get('vu_s_users')->num_rows();
		
		
		$data   = array();
		foreach($query as $result){
			$data[] = $result;
		}
		
		$json	= array(
						'success'   => TRUE,
						'message'   => "Loaded data",
						'total'     => $total,
						'data'      => $data
		);
		
		return $json;
	}
	
	/**
	 * Fungsi	: save
	 * 
	 * Untuk menambah data baru atau mengubah data lama
	 * 
	 * @param array $data
	 * @return json
	 */
	function save($data){
		$last   = NULL;
		
		$pkey = array('user_id'=>$data->USER_ID);
		$pass = $this->db->get_where('s_users', $pkey)->result();
		
		if($this->db->get_where('s_users', $pkey)->num_rows() > 0){
			/*
			 * Data Exist
			 */	
			
			if($data->NEW_PASS == $data->CONF_PASS && md5($data->USER_PASSWD) == $pass[0]->user_passwd)
			{			
				$arrdatau = array('user_name'=>$data->USER_NAME,'user_passwd'=>md5($data->NEW_PASS));
				 
				$this->db->where($pkey)->update('s_users', $arrdatau);
				$last   = $data;
				
				$total  = $this->db->get_where('s_users', $pkey)->num_rows();
				
				$json   = array(
					"success"   => TRUE,
					"message"   => 'Password Changed',
					'total'     => $total,
					"data"      => $last
				);
				
				return $json;
			}
			else
			{		
				$total  = $this->db->get_where('s_users', $pkey)->num_rows();
				
				$json   = array(
					"success"   => FALSE,
					"message"   => 'Password Fail'
				);
				
				return $json;
			}
			
		}
	}
	
	/**
	 * Fungsi	: delete
	 * 
	 * Untuk menghapus satu data
	 * 
	 * @param array $data
	 * @return json
	 */
	function delete($data){
		$pkey = array('user_id'=>$data->user_id);
		
		$this->db->where($pkey)->delete('s_users');
		
		$total  = $this->db->get('s_users')->num_rows();
		$last = $this->db->get('s_users')->result();
		
		$json   = array(
						"success"   => TRUE,
						"message"   => 'Data berhasil dihapus',
						'total'     => $total,
						"data"      => $last
		);				
		return $json;
	}
}
?>